package com.example.spring_seatreservation.controller;

import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/file")
public class FileController {
    /**
     * 方法一图片上传
     */
    @PostMapping("/uploads")
    public String uploads(MultipartFile file) throws IOException {

        if (file.isEmpty()) {
            return "图片上传失败！";
        }

        // file重命名
        String originalFilename = file.getOriginalFilename(); //原来图片名字
        String ext = "." + originalFilename.split("\\.")[1]; //1.png
        String uuid = UUID.randomUUID().toString().replace("-","");
        String fileName = uuid + ext;
        //上传图片
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
                "\\src\\main\\resources\\static\\images\\";
        String path = pre + fileName;
        try {
            file.transferTo(new File(path));
            return "/images/" + fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "图片上传失败！";
    }

    /**
     * 方法二图片上传
     */
    @PostMapping("/uploadimg")
    public String uploadimg(MultipartFile file) throws IOException {
        // 定义存储图片的地址
        String folder = "D:/imgs";
        // 文件夹
        File imgFolder = new File(folder);
        // 获取文件名
        String fname = file.getOriginalFilename();
        // 获取文件后缀
        String ext = "." + fname.substring(fname.lastIndexOf(".")+1);
        // 获取时间字符串
        String dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now());
        // 生成新的文件名
        String newFileName = dateTimeFormatter + UUID.randomUUID().toString().replaceAll("-","") + ext;
        // 文件在本机的全路径
        File filePath = new File(imgFolder, newFileName);
        if (!filePath.getParentFile().exists()){
            filePath.getParentFile().mkdirs();
        }
        try{
            file.transferTo(filePath);
            // 返回文件名
            return filePath.getName();
        }catch (IOException e){
            e.printStackTrace();
            return "";
        }
    }

}
